package com.md.domain.strategy;

import com.md.application.assembler.RoleApiAssembler;
import com.md.domain.model.bo.RoleBo;
import com.md.domain.model.po.Role;
import com.md.domain.model.po.RoleApis;
import com.md.model.po.Apis;
import com.md.repository.ApiRepository;
import com.md.repository.RoleApiRepository;
import com.md.repository.RoleRepository;
import com.md.strategy.Strategy;
import com.md.value.constants.AuthenticationConstants;
import com.md.value.enums.AuthEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * @author 刘骄阳
 * 2023-10-10 18:30
 */
@Slf4j
@Component("roleStrategy")
@RequiredArgsConstructor
public class RoleAfterStrategy implements Strategy<RoleBo> {
  private final RoleRepository roleRepository;
  private final ApiRepository apiRepository;
  private final RoleApiRepository roleApiRepository;

  /**
   * 后置处理,新增
   *
   * @param roleBo 角色新增bo
   */
  @Override
  public void asyncAfter(final RoleBo roleBo) {
    log.info("角色后置处理器");
    Role role = roleBo.getRole();
    List<RoleApis> addRoleApisList = roleBo.getAddRoleApisList();
    if (Objects.equals(AuthenticationConstants.DEFAULT_ROLE_PARENT_ID, role.getParentId())) {
      // 说明是根级
      role.setRootId(role.getId());
      roleRepository.update(role);
    }
    List<Apis> apisList = apiRepository.selectList(Apis.builder().auth(AuthEnum.OPEN.getCode()).build());
    RoleApiAssembler.buildAndAddRoleApisList(addRoleApisList, apisList);
    addRoleApisList.forEach(roleApis -> roleApis.setRoleId(role.getId()));
    roleApiRepository.insertBatch(addRoleApisList);
  }
}
